import {
  Button,
  Card,
  Col,
  Drawer,
  Form,
  Input,
  InputNumber,
  message,
  Row,
  Select,
  Space,
  Spin,
  Table,
} from "antd";
import Decimal from "decimal.js";
import { MyModalProps } from "types/modal";
import { formGutter, gutter } from "../const/keys";
import { useEffect, useState } from "react";
import {
  DeleteOutlined,
  EditOutlined,
  MinusOutlined,
  PlusOutlined,
  SearchOutlined,
} from "@ant-design/icons";
import PopconfirmButton from "@/components/PopconfirmButton";
import { formatData, getRandomId, sleep } from "@/utils";
import SelectProduct from "./SelectProduct";
import {
  QuotationItem,
  saveQuotation,
  QuotationTable,
  getQuotationDetail,
  initQuotationData,
  QuotationCategoryDetail,
} from "@/services/quotation";
import { templateOptions } from "./const";
import styles from "./index.modules.less";
import CheckboxInput from "./CheckboxInput";
import Dev from "./Dev";

type Props = MyModalProps & {
  businessOpportunityId: number;
  quantityId?: number;
  readOnly?: boolean;
};
const App = (props: Props) => {
  const {
    readOnly,
    businessOpportunityId,
    quantityId,
    onClose = () => {},
  } = props;
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [saveLoading, setSaveLoading] = useState(false);
  const [openProduct, setOpenProduct] = useState(false);
  const [ids, setIds] = useState<string | number[]>([]);
  const [detail, setDetail] = useState({});
  const [quotationTotalPrice, setQuotationTotalPrice] = useState(0); // 报价单合计，单位分
  const [quotationDiscountRate, setQuotationDiscountRate] = useState(0); //折扣率
  const [quotationDiscountPrice, setQuotationDiscountPrice] = useState(0); //报价单优惠至,单位分
  //利润率 当前利润率=（销售价-成本价）/成本价
  const [quotationProfitRate, setQuotationProfitRate] = useState(50);
  // 成本价 产品供货价* 数量 + 项目费用
  const [quotationCostPrice, setQuotationCostPrice] = useState(0);
  //销售价 销售价- （如果有优惠价，使用，否则就是项目合计 总和）
  const [quotationSellingPrice, setQuotationSellingPrice] = useState(0);

  const initData = async () => {
    if (quantityId !== undefined) {
      return;
    }
    const { data } = await initQuotationData(businessOpportunityId);
    const { quotationNumber, quotationFile } = data || {};
    form.setFieldsValue({ quotationNumber, quotationFile });
  };
  const [quotationTableList, setQuotationTableList] = useState<
    QuotationTable[]
  >([]);

  const getData = async (quantityId: number) => {
    try {
      setLoading(true);
      const { data, success, msg } = await getQuotationDetail(quantityId);
      if (success) {
        const { quotationName, quotationFile, quotationNumber, templateType } =
          data;
        form.setFieldsValue({
          quotationName,
          quotationFile,
          quotationNumber,
          templateType,
        });
        setDetail(data);
        setQuotationTotalPrice(data.quotationTotalPrice);
        setQuotationDiscountRate(data.quotationDiscountRate || 80);
        setQuotationDiscountPrice(data.quotationDiscountPrice);
        setQuotationTableList(data.quotationTableList);
      } else {
        message.error(msg || "获取报价单详情失败");
      }
      setLoading(false);
      // console.log(quotationTableList, data);
    } catch (error) {}
  };
  useEffect(() => {
    if (quantityId !== undefined) {
      getData(quantityId);
    } else {
      setQuotationTableList([
        {
          costItemList: [
            {
              costItemCalculateResult: 0,
              costItemName: "",
              costItemValue: 0,
              id: getRandomId(),
              quotationTableId: undefined,
              remark: "",
            },
          ],
          discountProductPrice: 0,
          id: getRandomId(),
          quotationId: 0,
          quotationTableCategorieList: [addQuotationTableCategorieListItem()],
          quotationTableName: "",
          remark: "",
          totalProductPrice: 0,
          totalProjectPrice: 0,
        },
      ]);
    }
  }, [quantityId]);
  const caleRate = () => {
    const quotationProfitRate =
      (quotationSellingPrice - quotationCostPrice) / quotationCostPrice;
    setQuotationProfitRate(quotationProfitRate * 100);
  };
  useEffect(() => {
    console.log(
      "quotationSellingPrice, quotationDiscountPrice, quotationCostPrice"
    );
    caleRate();
  }, [quotationSellingPrice, quotationDiscountPrice, quotationCostPrice]);
  useEffect(() => {
    initData();
  }, []);

  const addQuotationCostItem = () => {
    return {
      costItemCalculateResult: 0,
      costItemName: "",
      costItemValue: 0,
      id: getRandomId(),
      quotationTableId: undefined,
      remark: "",
    };
  };
  const addquotationTableCategorieDetailListItem = () => {
    return {
      id: getRandomId(),
      modelSpecification: "",
      originalGuidancePrice: 0,
      originalSupplyPrice: 0,
      originalUnit: "",
      productId: 0,
      productName: "",
      quantity: undefined,
      quotationTableCategoryId: 0,
      quotationTableId: 0,
      remark: "",
      sellingPrice: undefined,
    };
  };
  const addQuotationTableCategorieListItem = () => {
    return {
      categoryTotalPrice: 0,
      id: getRandomId(),
      quotationTableCategorieDetailList: [
        addquotationTableCategorieDetailListItem(),
      ],
      quotationTableCategoryName: "",
      quotationTableId: 0,
      remark: "",
    };
  };
  const addTableItem = () => {
    return {
      costItemList: [
        {
          costItemCalculateResult: 0,
          costItemName: "",
          costItemValue: 0,
          // createBy: "",
          id: getRandomId(),
          quotationTableId: 0,
          // remark: "",
        },
      ],
      discountProductPrice: 0,
      id: getRandomId(),
      quotationId: 0,
      quotationTableCategorieList: [addQuotationTableCategorieListItem()],
      quotationTableName: "",
      remark: "",
      totalProductPrice: 0,
      totalProjectPrice: 0,
    };
  };
  const add = async () => {
    await form.validateFields();
    const { quotationName, quotationFile, quotationNumber, templateType } =
      form.getFieldsValue();

    const formData: QuotationItem = {
      ...detail,
      businessOpportunityId,
      quotationTableList,
      quotationDiscountPrice,
      quotationDiscountRate,
      quotationFile, //
      quotationName, //
      templateType, //
      quotationNumber, //
      quotationTotalPrice,
      remark: "", //
    };
    const submitData: QuotationItem = JSON.parse(JSON.stringify(formData));

    //如果ID不是number就删除，是number就不动
    if (typeof submitData.id !== "number") {
      submitData.id = undefined as any;
    }
    submitData.quotationTableList = submitData.quotationTableList.map(
      (table) => {
        table.costItemList = table.costItemList.map((costItem) => {
          if (typeof costItem.id !== "number") {
            costItem.id = undefined as any;
          }
          return costItem;
        });
        // table.costItemList = [];
        if (typeof table.id !== "number") {
          table.id = undefined as any;
        }
        table.quotationTableCategorieList =
          table.quotationTableCategorieList.map((category) => {
            if (typeof category.id !== "number") {
              category.id = undefined as any;
            }
            category.quotationTableCategorieDetailList =
              category.quotationTableCategorieDetailList.map((detail) => {
                console.log(detail);
                if (typeof detail.id !== "number") {
                  detail.id = undefined as any;
                }
                return detail;
              });
            return category;
          });
        return table;
      }
    );

    // submitData.quotationTableList = [];
    console.log("submitData", submitData, JSON.stringify(submitData));
    setSaveLoading(true);
    const { success } = await saveQuotation(submitData);
    if (success) {
      message.success("保存成功");
      onClose(true);
    }
    setSaveLoading(false);
  };
  const calcData = async (timeout = 0) => {
    await sleep(timeout);
    let _list = [...quotationTableList];
    // 计算costItemList的costItemCalculateResult
    const totalPriceList = [0];
    //成本价    产品供货价* 数量 + 项目费用    + 多表
    //供货价格
    const supplyPriceList = [0];
    // 项目费用
    const projectCostList = [0];
    //销售价= totalProjectPrice 销售价- （如果有优惠价，使用，否则就是项目合计 总和）
    const sellingPriceList = [0]; //有discountProductPrice，就使用，否则使用totalProjectPrice
    _list = _list.map((quotationTableItem) => {
      const productPriceList = [0];
      const quotationTableCategorieList =
        quotationTableItem.quotationTableCategorieList.map(
          (quotationTableCategorieItem) => {
            const priceList = [0];
            const quotationTableCategorieDetailList =
              quotationTableCategorieItem.quotationTableCategorieDetailList.map(
                (quotationTableCategorieDetailItem) => {
                  const {
                    sellingPrice = 0,
                    quantity = 0,
                    originalSupplyPrice,
                  } = quotationTableCategorieDetailItem;
                  priceList.push(sellingPrice * quantity);
                  supplyPriceList.push(originalSupplyPrice * quantity);
                  return { ...quotationTableCategorieDetailItem };
                }
              );
            const categoryTotalPrice = priceList.reduce((a, b) => a + b, 0);
            productPriceList.push(categoryTotalPrice);
            return {
              ...quotationTableCategorieItem,
              categoryTotalPrice,
              quotationTableCategorieDetailList,
            };
          }
        );
      const totalProductPrice = productPriceList.reduce((a, b) => a + b, 0);
      const costPriceList = [0];
      //计算总价
      if (quotationTableItem.discountProductPrice > 0) {
        totalPriceList.push(quotationTableItem.discountProductPrice);
      } else {
        totalPriceList.push(quotationTableItem.totalProjectPrice);
      }
      //费用项
      const costItemList = quotationTableItem.costItemList.map((costItem) => {
        //使用Decimal.js避免浮点运算误差,
        // const costItemCalculateResult =
        //   totalProductPrice * (costItem.costItemValue / 100);
        const costItemCalculateResult = new Decimal(totalProductPrice)
          .mul(new Decimal(costItem.costItemValue).div(100))
          .toNumber();
        projectCostList.push(costItemCalculateResult);
        costPriceList.push(costItemCalculateResult);
        return { ...costItem, costItemCalculateResult };
      });

      const totalProjectPrice =
        totalProductPrice + costPriceList.reduce((a, b) => a + b, 0);
      if (costPriceList?.length > 1) {
        projectCostList.push(costPriceList.reduce((a, b) => a + b, 0));
      } else {
        projectCostList.push(totalProjectPrice);
      }
      if (quotationTableItem.discountProductPrice > 0) {
        sellingPriceList.push(quotationTableItem.discountProductPrice);
      } else {
        sellingPriceList.push(totalProjectPrice);
      }
      return {
        ...quotationTableItem,
        costItemList,
        totalProjectPrice,
        totalProductPrice,
        quotationTableCategorieList,
      };
    });
    // setQuotationSellingPrice(sellingPriceList.reduce((a, b) => a + b, 0));
    setQuotationCostPrice(
      projectCostList.reduce((a, b) => a + b, 0) +
        supplyPriceList.reduce((a, b) => a + b, 0)
    );
    // console.log(projectCostList,supplyPriceList.reduce((a, b) => a + b, 0));
    const quotationTotalPrice = totalPriceList.reduce((a, b) => a + b, 0);
    let quotationDiscountRate = quotationDiscountPrice / quotationTotalPrice; //
    setQuotationDiscountRate(quotationDiscountRate);
    setQuotationTableList(_list);
    setQuotationTotalPrice(quotationTotalPrice);
    quotationTotalPrice;

    setQuotationSellingPrice(quotationDiscountPrice || quotationTotalPrice);
  };
  useEffect(() => {
    calcData();
    caleRate();
  }, [JSON.stringify(quotationTableList)]);
  return (
    <>
      <Drawer
        title="报价单详情"
        width={1400}
        open
        onClose={() => {
          onClose(false);
        }}
        footer={
          <Row gutter={[gutter, gutter]} justify="end">
            <Col>
              <Button
                onClick={() => {
                  onClose();
                }}
              >
                取消
              </Button>
            </Col>
            {readOnly ? null : (
              <Col>
                <Button
                  disabled={saveLoading || saveLoading}
                  loading={saveLoading}
                  type="primary"
                  onClick={add}
                >
                  保存
                </Button>
              </Col>
            )}
          </Row>
        }
      >
        <Spin spinning={loading}>
          <Row gutter={[gutter, gutter]}>
            <Col span={24}>
              <Form form={form}>
                <Row gutter={[gutter, gutter]}>
                  <Col span={6}>
                    <Form.Item
                      label="报价单名称"
                      name="quotationName"
                      rules={[
                        {
                          required: true,
                        },
                      ]}
                    >
                      <Input
                        placeholder="请输入报价单名称"
                        disabled={readOnly}
                      />
                    </Form.Item>
                  </Col>
                  <Col span={6}>
                    <Form.Item
                      label="模板"
                      name="templateType"
                      initialValue={1}
                      rules={[
                        {
                          required: true,
                        },
                      ]}
                    >
                      <Select
                        style={{
                          width: "100%",
                        }}
                        disabled={readOnly}
                        options={templateOptions}
                        placeholder="请选择模板"
                      />
                    </Form.Item>
                  </Col>
                  <Col span={6}>
                    {/* 单号 */}
                    <Form.Item
                      label="单号"
                      name="quotationNumber"
                      rules={[
                        {
                          required: true,
                        },
                      ]}
                    >
                      <Input disabled placeholder="请输入单号" />
                    </Form.Item>
                  </Col>
                  <Col span={6}>
                    {/* 客户 */}
                    <Form.Item
                      label="文件名称"
                      name="quotationFile"
                      rules={[
                        {
                          required: true,
                        },
                      ]}
                    >
                      <Input disabled placeholder="请输入文件名称" />
                    </Form.Item>
                  </Col>
                </Row>
              </Form>
            </Col>

            <Col span={24}>
              <Row gutter={[gutter, gutter]}>
                {/* <Dev>quotationTableList</Dev> */}
                {quotationTableList?.map(
                  (quotationTable, quotationTableIndex) => {
                    return (
                      <Col span={24} key={quotationTable.id}>
                        <Card
                          extra={
                            <Button
                              size="small"
                              type="primary"
                              ghost
                              danger
                              disabled={
                                quotationTableList.length <= 1 || readOnly
                              }
                              icon={<DeleteOutlined />}
                              onClick={() => {
                                const _list = [...quotationTableList];
                                const index = _list.findIndex(
                                  (i) => i.id === quotationTable.id
                                );
                                if (index > -1) {
                                  _list.splice(index, 1);
                                  setQuotationTableList(_list);
                                }
                              }}
                            >
                              删除表
                            </Button>
                          }
                        >
                          <Row gutter={[gutter, gutter]}>
                            <Col span={24}>
                              <Form layout="inline" form={form}>
                                <Form.Item
                                  label="表称"
                                  initialValue={
                                    quotationTable.quotationTableName
                                  }
                                  name={`projectName-${quotationTable.id}-${quotationTableIndex}`}
                                  rules={[
                                    {
                                      required: true,
                                    },
                                  ]}
                                >
                                  <Input
                                    placeholder="请输入表名"
                                    disabled={readOnly}
                                    onChange={(ev) => {
                                      const newValue = ev.target.value;
                                      let _list = [...quotationTableList];
                                      _list = _list.map((_quotationTable) => {
                                        if (
                                          quotationTable.id ===
                                          _quotationTable.id
                                        ) {
                                          _quotationTable.quotationTableName =
                                            newValue;
                                        }
                                        return { ..._quotationTable };
                                      });
                                      setQuotationTableList(_list);
                                    }}
                                  />
                                </Form.Item>
                              </Form>
                            </Col>

                            <Col span={24}>
                              {/* <Dev>quotationTableCategorieList</Dev> */}
                              <Row gutter={[gutter, gutter]}>
                                {quotationTable.quotationTableCategorieList?.map(
                                  (quotationTableCategorieItem, index) => {
                                    const key = `${quotationTable.id}-${quotationTableCategorieItem.id}-${index}`;
                                    return (
                                      <Col span={24} key={key}>
                                        <Card
                                          size="small"
                                          title="功能类别"
                                          extra={
                                            <PopconfirmButton
                                              danger
                                              size="small"
                                              //保留一个
                                              disabled={
                                                quotationTable
                                                  .quotationTableCategorieList
                                                  .length <= 1 || readOnly
                                              }
                                              onConfirm={() => {
                                                // 删除类别
                                                const _list = [
                                                  ...quotationTableList,
                                                ];
                                                _list.forEach((table) => {
                                                  if (
                                                    table.id ===
                                                    quotationTable.id
                                                  ) {
                                                    const index =
                                                      table.quotationTableCategorieList.findIndex(
                                                        (i) =>
                                                          i.id ===
                                                          quotationTable
                                                            .quotationTableCategorieList[
                                                            quotationTable
                                                              .quotationTableCategorieList
                                                              .length - 1
                                                          ].id
                                                      );
                                                    if (index > -1) {
                                                      table.quotationTableCategorieList.splice(
                                                        index,
                                                        1
                                                      );
                                                    }
                                                  }
                                                });
                                                setQuotationTableList(_list);
                                                // calcData();
                                              }}
                                            >
                                              删除类别
                                            </PopconfirmButton>
                                          }
                                        >
                                          <Row gutter={[gutter, gutter]}>
                                            <Col span={24}>
                                              <Dev>
                                                quotationTableCategorieDetailList
                                                {JSON.stringify(
                                                  quotationTableCategorieItem.quotationTableCategorieDetailList
                                                )}
                                              </Dev>

                                              <Table
                                                pagination={false}
                                                rowKey={`${quotationTableCategorieItem.id}-table-${index}`}
                                                dataSource={
                                                  quotationTableCategorieItem.quotationTableCategorieDetailList
                                                }
                                                columns={[
                                                  {
                                                    title: "产品名称",
                                                    dataIndex: "productName",
                                                    key: "productName",
                                                    render: (
                                                      productName,
                                                      record
                                                    ) => {
                                                      return (
                                                        <Form form={form}>
                                                          <Form.Item
                                                            noStyle
                                                            initialValue={
                                                              productName
                                                            }
                                                            name={`${quotationTable.id}-${quotationTableCategorieItem.id}-${record.id}-productName`}
                                                            label="产品名称"
                                                            rules={[
                                                              {
                                                                required: true,
                                                              },
                                                            ]}
                                                          >
                                                            <Input
                                                              size="small"
                                                              disabled={
                                                                readOnly
                                                              }
                                                              onChange={(
                                                                ev
                                                              ) => {
                                                                const newValue =
                                                                  ev.target
                                                                    .value;
                                                                let _list = [
                                                                  ...quotationTableList,
                                                                ];
                                                                _list =
                                                                  _list.map(
                                                                    (
                                                                      _quotationTable
                                                                    ) => {
                                                                      if (
                                                                        quotationTable.id ===
                                                                        _quotationTable.id
                                                                      ) {
                                                                        _quotationTable.quotationTableCategorieList =
                                                                          _quotationTable.quotationTableCategorieList.map(
                                                                            (
                                                                              _category
                                                                            ) => {
                                                                              if (
                                                                                _category.id ===
                                                                                quotationTableCategorieItem.id
                                                                              ) {
                                                                                _category.quotationTableCategorieDetailList =
                                                                                  _category.quotationTableCategorieDetailList.map(
                                                                                    (
                                                                                      _detail
                                                                                    ) => {
                                                                                      if (
                                                                                        _detail.id ===
                                                                                        record.id
                                                                                      ) {
                                                                                        return {
                                                                                          ..._detail,
                                                                                          productName:
                                                                                            newValue,
                                                                                        };
                                                                                      }
                                                                                      return {
                                                                                        ..._detail,
                                                                                      };
                                                                                    }
                                                                                  );
                                                                              }
                                                                              return {
                                                                                ..._category,
                                                                              };
                                                                            }
                                                                          );
                                                                      }
                                                                      return {
                                                                        ..._quotationTable,
                                                                      };
                                                                    }
                                                                  );
                                                                setQuotationTableList(
                                                                  _list
                                                                );
                                                              }}
                                                              placeholder="请输入产品名称"
                                                            />
                                                          </Form.Item>
                                                        </Form>
                                                      );
                                                    },
                                                  },
                                                  {
                                                    title: "型号描述",
                                                    key: "modelSpecification",
                                                    dataIndex:
                                                      "modelSpecification",
                                                    render: (
                                                      modelSpecification,
                                                      record
                                                    ) => {
                                                      return (
                                                        <Row
                                                          gutter={[
                                                            formGutter,
                                                            formGutter,
                                                          ]}
                                                        >
                                                          <Col>
                                                            <Form form={form}>
                                                              <Form.Item
                                                                noStyle
                                                                initialValue={
                                                                  modelSpecification
                                                                }
                                                                name={`${quotationTable.id}-${quotationTableCategorieItem.id}-${record.id}-modelSpecification`}
                                                                label="型号描述"
                                                                rules={[
                                                                  {
                                                                    required:
                                                                      true,
                                                                  },
                                                                ]}
                                                              >
                                                                <Input
                                                                  disabled={
                                                                    readOnly
                                                                  }
                                                                  size="small"
                                                                  defaultValue={
                                                                    modelSpecification
                                                                  }
                                                                  value={
                                                                    modelSpecification
                                                                  }
                                                                  onChange={(
                                                                    ev
                                                                  ) => {
                                                                    const newValue =
                                                                      ev.target
                                                                        .value;
                                                                    let _list =
                                                                      [
                                                                        ...quotationTableList,
                                                                      ];
                                                                    _list =
                                                                      _list.map(
                                                                        (
                                                                          _quotationTable
                                                                        ) => {
                                                                          if (
                                                                            quotationTable.id ===
                                                                            _quotationTable.id
                                                                          ) {
                                                                            _quotationTable.quotationTableCategorieList =
                                                                              _quotationTable.quotationTableCategorieList.map(
                                                                                (
                                                                                  _category
                                                                                ) => {
                                                                                  if (
                                                                                    _category.id ===
                                                                                    quotationTableCategorieItem.id
                                                                                  ) {
                                                                                    _category.quotationTableCategorieDetailList =
                                                                                      _category.quotationTableCategorieDetailList.map(
                                                                                        (
                                                                                          _detail
                                                                                        ) => {
                                                                                          if (
                                                                                            _detail.id ===
                                                                                            record.id
                                                                                          ) {
                                                                                            return {
                                                                                              ..._detail,
                                                                                              modelSpecification:
                                                                                                newValue,
                                                                                            };
                                                                                          }
                                                                                          return {
                                                                                            ..._detail,
                                                                                          };
                                                                                        }
                                                                                      );
                                                                                  }
                                                                                  return {
                                                                                    ..._category,
                                                                                  };
                                                                                }
                                                                              );
                                                                          }
                                                                          return {
                                                                            ..._quotationTable,
                                                                          };
                                                                        }
                                                                      );
                                                                    setQuotationTableList(
                                                                      _list
                                                                    );
                                                                  }}
                                                                  placeholder="请输入型号描述"
                                                                />
                                                              </Form.Item>
                                                            </Form>
                                                          </Col>
                                                          <Col>
                                                            <Button
                                                              type="primary"
                                                              ghost
                                                              disabled={
                                                                readOnly
                                                              }
                                                              size="small"
                                                              onClick={() => {
                                                                setOpenProduct(
                                                                  true
                                                                );
                                                                setIds([
                                                                  quotationTable.id,
                                                                  quotationTableCategorieItem.id,
                                                                  record.id,
                                                                ]);
                                                              }}
                                                              icon={
                                                                <SearchOutlined />
                                                              }
                                                            >
                                                              查询
                                                            </Button>
                                                          </Col>
                                                        </Row>
                                                      );
                                                    },
                                                  },
                                                  {
                                                    title: "售价",
                                                    dataIndex: "sellingPrice",
                                                    key: "sellingPrice",
                                                    render: (
                                                      sellingPrice,
                                                      record
                                                    ) => {
                                                      return (
                                                        <Form form={form}>
                                                          <Form.Item
                                                            name={`${quotationTable.id}-${quotationTableCategorieItem.id}-${record.id}-sellingPrice-${index}`}
                                                            noStyle
                                                            rules={[
                                                              {
                                                                required: true,
                                                              },
                                                            ]}
                                                            initialValue={
                                                              sellingPrice
                                                                ? (sellingPrice ||
                                                                    0) / 100
                                                                : undefined
                                                            }
                                                          >
                                                            <InputNumber
                                                              size="small"
                                                              addonAfter="元"
                                                              placeholder="售价"
                                                              disabled={
                                                                readOnly
                                                              }
                                                              min={0}
                                                              style={{
                                                                width: 145,
                                                              }}
                                                              onChange={(
                                                                ev
                                                              ) => {
                                                                var _newValue =
                                                                  ev;
                                                                let _list = [
                                                                  ...quotationTableList,
                                                                ];
                                                                _list =
                                                                  _list.map(
                                                                    (
                                                                      _quotationTable
                                                                    ) => {
                                                                      if (
                                                                        quotationTable.id ===
                                                                        _quotationTable.id
                                                                      ) {
                                                                        _quotationTable.quotationTableCategorieList =
                                                                          _quotationTable.quotationTableCategorieList.map(
                                                                            (
                                                                              _category
                                                                            ) => {
                                                                              if (
                                                                                _category.id ===
                                                                                quotationTableCategorieItem.id
                                                                              ) {
                                                                                _category.quotationTableCategorieDetailList =
                                                                                  _category.quotationTableCategorieDetailList.map(
                                                                                    (
                                                                                      _detail
                                                                                    ) => {
                                                                                      if (
                                                                                        _detail.id ===
                                                                                        record.id
                                                                                      ) {
                                                                                        return {
                                                                                          ..._detail,
                                                                                          sellingPrice:
                                                                                            (_newValue ||
                                                                                              0) *
                                                                                            100,
                                                                                        };
                                                                                      }
                                                                                      return {
                                                                                        ..._detail,
                                                                                      };
                                                                                    }
                                                                                  );
                                                                              }
                                                                              return {
                                                                                ..._category,
                                                                              };
                                                                            }
                                                                          );
                                                                      }
                                                                      return {
                                                                        ..._quotationTable,
                                                                      };
                                                                    }
                                                                  );
                                                                setQuotationTableList(
                                                                  _list
                                                                );
                                                                // calcData();
                                                              }}
                                                              //保留两位小数
                                                              precision={2}
                                                            />
                                                          </Form.Item>
                                                        </Form>
                                                      );
                                                    },
                                                  },
                                                  {
                                                    title: "数量",
                                                    dataIndex: "quantity",
                                                    key: "quantity",
                                                    render: (
                                                      quantity,
                                                      record
                                                    ) => {
                                                      return (
                                                        <Form form={form}>
                                                          <Form.Item
                                                            rules={[
                                                              {
                                                                required: true,
                                                              },
                                                            ]}
                                                            name={`${quotationTable.id}-${quotationTableCategorieItem.id}-${record.id}-quantity-${index}`}
                                                            noStyle
                                                            initialValue={
                                                              quantity
                                                            }
                                                          >
                                                            <InputNumber
                                                              size="small"
                                                              placeholder="数量"
                                                              min={0}
                                                              disabled={
                                                                readOnly
                                                              }
                                                              precision={0}
                                                              style={{
                                                                width: 60,
                                                              }}
                                                              onChange={(
                                                                ev
                                                              ) => {
                                                                var _newValue =
                                                                  ev;
                                                                let _list = [
                                                                  ...quotationTableList,
                                                                ];
                                                                _list =
                                                                  _list.map(
                                                                    (
                                                                      _quotationTable
                                                                    ) => {
                                                                      if (
                                                                        quotationTable.id ===
                                                                        _quotationTable.id
                                                                      ) {
                                                                        _quotationTable.quotationTableCategorieList =
                                                                          _quotationTable.quotationTableCategorieList.map(
                                                                            (
                                                                              _category
                                                                            ) => {
                                                                              if (
                                                                                _category.id ===
                                                                                quotationTableCategorieItem.id
                                                                              ) {
                                                                                _category.quotationTableCategorieDetailList =
                                                                                  _category.quotationTableCategorieDetailList.map(
                                                                                    (
                                                                                      _detail
                                                                                    ) => {
                                                                                      if (
                                                                                        _detail.id ===
                                                                                        record.id
                                                                                      ) {
                                                                                        return {
                                                                                          ..._detail,
                                                                                          quantity:
                                                                                            _newValue ||
                                                                                            0,
                                                                                        };
                                                                                      }
                                                                                      return {
                                                                                        ..._detail,
                                                                                      };
                                                                                    }
                                                                                  );
                                                                              }
                                                                              return {
                                                                                ..._category,
                                                                              };
                                                                            }
                                                                          );
                                                                      } else {
                                                                        return {
                                                                          ..._quotationTable,
                                                                        };
                                                                      }
                                                                      return {
                                                                        ..._quotationTable,
                                                                      };
                                                                    }
                                                                  );
                                                                setQuotationTableList(
                                                                  _list
                                                                );
                                                                // calcData();
                                                              }}
                                                            />
                                                          </Form.Item>
                                                        </Form>
                                                      );
                                                    },
                                                  },
                                                  {
                                                    title: "单位",
                                                    dataIndex: "originalUnit",
                                                    key: "originalUnit",
                                                    minWidth: 50,
                                                    render: (originalUnit) => {
                                                      return formatData(
                                                        originalUnit
                                                      );
                                                    },
                                                  },
                                                  // 金额
                                                  {
                                                    title: "金额",
                                                    dataIndex:
                                                      "originalGuidancePrice",
                                                    key: "originalGuidancePrice",
                                                    render: (
                                                      originalGuidancePrice
                                                    ) => {
                                                      return formatData(
                                                        (
                                                          (originalGuidancePrice ||
                                                            0) / 100
                                                        ).toFixed(2)
                                                      );
                                                    },
                                                    minWidth: 100,
                                                  },
                                                  //edit
                                                  {
                                                    title: "操作",
                                                    minWidth: 150,
                                                    render: (_, record) => (
                                                      <Row
                                                        gutter={[
                                                          formGutter,
                                                          formGutter,
                                                        ]}
                                                      >
                                                        <Col>
                                                          <Button
                                                            key={"edit"}
                                                            size="small"
                                                            type="link"
                                                            disabled={readOnly}
                                                            icon={
                                                              <EditOutlined />
                                                            }
                                                            ghost
                                                            onClick={() => {
                                                              // 添加一行
                                                              const _list = [
                                                                ...quotationTableList,
                                                              ];
                                                              _list.forEach(
                                                                (_table) => {
                                                                  if (
                                                                    _table.id ===
                                                                    quotationTable.id
                                                                  ) {
                                                                    _table.quotationTableCategorieList.forEach(
                                                                      (
                                                                        _category
                                                                      ) => {
                                                                        if (
                                                                          _category.id ===
                                                                          quotationTableCategorieItem.id
                                                                        ) {
                                                                          _category.quotationTableCategorieDetailList.push(
                                                                            addquotationTableCategorieDetailListItem()
                                                                          );
                                                                        }
                                                                      }
                                                                    );
                                                                  }
                                                                }
                                                              );
                                                              setQuotationTableList(
                                                                _list
                                                              );
                                                              // calcData();
                                                            }}
                                                          >
                                                            添加
                                                          </Button>
                                                        </Col>
                                                        <Col>
                                                          <PopconfirmButton
                                                            disabled={
                                                              quotationTableCategorieItem
                                                                .quotationTableCategorieDetailList
                                                                ?.length <= 1 ||
                                                              readOnly
                                                            }
                                                            type="link"
                                                            key={"delete"}
                                                            size="small"
                                                            title="确认删除吗？"
                                                            icon={
                                                              <DeleteOutlined />
                                                            }
                                                            danger
                                                            onConfirm={() => {
                                                              const _list = [
                                                                ...quotationTableList,
                                                              ];
                                                              _list.map(
                                                                (
                                                                  _quotationTable
                                                                ) => {
                                                                  if (
                                                                    quotationTable.id ===
                                                                    _quotationTable.id
                                                                  ) {
                                                                    _quotationTable.quotationTableCategorieList =
                                                                      _quotationTable.quotationTableCategorieList.map(
                                                                        (
                                                                          _category
                                                                        ) => {
                                                                          if (
                                                                            _category.id ===
                                                                            quotationTableCategorieItem.id
                                                                          ) {
                                                                            _category.quotationTableCategorieDetailList =
                                                                              _category.quotationTableCategorieDetailList.filter(
                                                                                (
                                                                                  _detail
                                                                                ) => {
                                                                                  return (
                                                                                    _detail.id !==
                                                                                    record.id
                                                                                  );
                                                                                }
                                                                              );
                                                                          }
                                                                          return {
                                                                            ..._category,
                                                                          };
                                                                        }
                                                                      );
                                                                  }
                                                                  return {
                                                                    ..._quotationTable,
                                                                  };
                                                                }
                                                              );
                                                              setQuotationTableList(
                                                                _list
                                                              );
                                                              // calcData();
                                                            }}
                                                          >
                                                            删除
                                                          </PopconfirmButton>
                                                        </Col>
                                                      </Row>
                                                    ),
                                                  },
                                                ]}
                                              />
                                            </Col>
                                            <Col span={24}>
                                              <Row justify="end">
                                                <Col>
                                                  类别合计：¥{" "}
                                                  {(
                                                    (quotationTableCategorieItem.categoryTotalPrice ||
                                                      0) / 100
                                                  ).toFixed(2)}
                                                </Col>
                                              </Row>
                                            </Col>
                                          </Row>
                                        </Card>
                                      </Col>
                                    );
                                  }
                                )}
                              </Row>
                            </Col>

                            <Col span={24}>
                              <Button
                                type="primary"
                                disabled={readOnly}
                                ghost
                                size="small"
                                icon={<PlusOutlined />}
                                onClick={() => {
                                  let _list = [...quotationTableList];
                                  //在quotationTableCategorieList插入
                                  // addQuotationTableCategorieListItem()
                                  _list = _list.map((_quotationTable) => {
                                    if (
                                      quotationTable.id === _quotationTable.id
                                    ) {
                                      _quotationTable.quotationTableCategorieList.push(
                                        addQuotationTableCategorieListItem()
                                      );
                                    }
                                    return {
                                      ..._quotationTable,
                                    };
                                  });

                                  setQuotationTableList(_list);
                                }}
                              >
                                插入类别
                              </Button>
                            </Col>
                            <Col span={24}>
                              <Row justify="end">
                                <Col>
                                  <Row
                                    align="middle"
                                    style={{ width: 400 }}
                                    gutter={[gutter, formGutter]}
                                  >
                                    <Col span={24}>
                                      产品合计：¥{" "}
                                      {(
                                        (quotationTable.totalProductPrice ||
                                          0) / 100
                                      ).toFixed(2)}
                                    </Col>

                                    <Col span={24}>
                                      <Row gutter={[gutter, 0]}>
                                        {quotationTable.costItemList.map(
                                          (constItem) => {
                                            return (
                                              <Col span={24}>
                                                <Row
                                                  wrap={false}
                                                  align={"middle"}
                                                >
                                                  <Col>
                                                    <Space.Compact>
                                                      <Form form={form}>
                                                        <Form.Item
                                                          name={`${quotationTable.id}-costItemName-${constItem.id}`}
                                                          initialValue={
                                                            constItem.costItemName
                                                          }
                                                          rules={[
                                                            {
                                                              required: true,
                                                              message:
                                                                "输入费用项名称",
                                                            },
                                                          ]}
                                                        >
                                                          <Input
                                                            disabled={readOnly}
                                                            value={
                                                              constItem.costItemName
                                                            }
                                                            style={{
                                                              width: 100,
                                                            }}
                                                            placeholder="费用项名称"
                                                            onChange={(ev) => {
                                                              const newVal =
                                                                ev.target.value;
                                                              let _list = [
                                                                ...quotationTableList,
                                                              ];
                                                              _list = _list.map(
                                                                (
                                                                  _quotationTable
                                                                ) => {
                                                                  if (
                                                                    quotationTable.id ===
                                                                    _quotationTable.id
                                                                  ) {
                                                                    _quotationTable.costItemList =
                                                                      _quotationTable.costItemList.map(
                                                                        (
                                                                          _costItem
                                                                        ) => {
                                                                          if (
                                                                            _costItem.id ===
                                                                            constItem.id
                                                                          ) {
                                                                            return {
                                                                              ..._costItem,
                                                                              costItemName:
                                                                                newVal,
                                                                            };
                                                                          }
                                                                          return {
                                                                            ..._costItem,
                                                                          };
                                                                        }
                                                                      );
                                                                  }
                                                                  return {
                                                                    ..._quotationTable,
                                                                  };
                                                                }
                                                              );
                                                              setQuotationTableList(
                                                                _list
                                                              );
                                                            }}
                                                          />
                                                        </Form.Item>
                                                      </Form>
                                                      <Form form={form}>
                                                        <Form.Item
                                                          rules={[
                                                            {
                                                              required: true,
                                                              message:
                                                                "不能为空",
                                                            },
                                                          ]}
                                                          initialValue={
                                                            constItem.costItemValue
                                                          }
                                                          name={`${quotationTable.id}-costItemValue-${constItem.id}`}
                                                        >
                                                          <InputNumber
                                                            style={{
                                                              width: 120,
                                                            }}
                                                            disabled={readOnly}
                                                            addonAfter="%"
                                                            precision={2}
                                                            defaultValue={
                                                              constItem.costItemValue
                                                            }
                                                            min={0}
                                                            max={100}
                                                            placeholder="请输入税费"
                                                            onChange={(ev) => {
                                                              const newVal = ev;
                                                              let _list = [
                                                                ...quotationTableList,
                                                              ];
                                                              _list = _list.map(
                                                                (
                                                                  _quotationTable
                                                                ) => {
                                                                  if (
                                                                    quotationTable.id ===
                                                                    _quotationTable.id
                                                                  ) {
                                                                    _quotationTable.costItemList =
                                                                      _quotationTable.costItemList.map(
                                                                        (
                                                                          _costItem
                                                                        ) => {
                                                                          if (
                                                                            _costItem.id ===
                                                                            constItem.id
                                                                          ) {
                                                                            return {
                                                                              ..._costItem,
                                                                              costItemValue:
                                                                                newVal ||
                                                                                0,
                                                                            };
                                                                          }
                                                                          return {
                                                                            ..._costItem,
                                                                          };
                                                                        }
                                                                      );
                                                                  }
                                                                  return {
                                                                    ..._quotationTable,
                                                                  };
                                                                }
                                                              );
                                                              setQuotationTableList(
                                                                _list
                                                              );
                                                              // calcData();
                                                            }}
                                                          />
                                                        </Form.Item>
                                                      </Form>

                                                      <Input
                                                        disabled
                                                        value={
                                                          constItem.costItemCalculateResult /
                                                          100
                                                        }
                                                        defaultValue={0}
                                                        style={{ width: 130 }}
                                                        addonAfter="元"
                                                      />
                                                      <Button
                                                        // disabled={
                                                        //   quotationTable
                                                        //     .costItemList
                                                        //     ?.length <= 1
                                                        // }
                                                        icon={<MinusOutlined />}
                                                        onClick={() => {
                                                          //删除一项
                                                          let _list = [
                                                            ...quotationTableList,
                                                          ];
                                                          _list = _list.map(
                                                            (
                                                              _quotationTable
                                                            ) => {
                                                              if (
                                                                quotationTable.id ===
                                                                _quotationTable.id
                                                              ) {
                                                                _quotationTable.costItemList =
                                                                  _quotationTable.costItemList.filter(
                                                                    (
                                                                      _costItem
                                                                    ) => {
                                                                      return (
                                                                        _costItem.id !==
                                                                        constItem.id
                                                                      );
                                                                    }
                                                                  );
                                                              }
                                                              return {
                                                                ..._quotationTable,
                                                              };
                                                            }
                                                          );
                                                          setQuotationTableList(
                                                            _list
                                                          );
                                                          // calcData();
                                                        }}
                                                      ></Button>
                                                    </Space.Compact>
                                                  </Col>
                                                </Row>
                                              </Col>
                                            );
                                          }
                                        )}
                                      </Row>
                                    </Col>
                                    <Col span={24}>
                                      {/* quotationTable.costItemList */}
                                      <Button
                                        icon={<PlusOutlined />}
                                        size="small"
                                        type="primary"
                                        disabled={readOnly}
                                        ghost
                                        onClick={() => {
                                          //quotationTable.costItemList 添加一项
                                          let _list = [...quotationTableList];
                                          _list = _list.map(
                                            (_quotationTable) => {
                                              if (
                                                quotationTable.id ===
                                                _quotationTable.id
                                              ) {
                                                _quotationTable.costItemList.push(
                                                  addQuotationCostItem()
                                                );
                                              }
                                              return {
                                                ..._quotationTable,
                                              };
                                            }
                                          );
                                          setQuotationTableList(_list);
                                        }}
                                      >
                                        添加费用项
                                      </Button>
                                    </Col>
                                    <Col span={24}>
                                      项目合计：¥{" "}
                                      {(
                                        (quotationTable.totalProjectPrice ||
                                          0) / 100
                                      ).toFixed(2)}
                                    </Col>
                                    <Col span={24}>
                                      <CheckboxInput
                                        disabled={readOnly}
                                        defaultValue={
                                          quotationTable.discountProductPrice /
                                          100
                                        }
                                        onChange={(val) => {
                                          let _list = [...quotationTableList];
                                          _list = _list.map(
                                            (_quotationTable) => {
                                              if (
                                                quotationTable.id ===
                                                _quotationTable.id
                                              ) {
                                                _quotationTable.discountProductPrice =
                                                  (100 * (val || 0)) as number;
                                              }
                                              return {
                                                ..._quotationTable,
                                              };
                                            }
                                          );
                                          setQuotationTableList(_list);
                                          // calcData();
                                        }}
                                      />
                                    </Col>
                                  </Row>
                                </Col>
                              </Row>
                            </Col>
                          </Row>
                        </Card>
                      </Col>
                    );
                  }
                )}
              </Row>
            </Col>
            <Col span={24}>
              <Button
                type="primary"
                ghost
                icon={<PlusOutlined />}
                disabled={readOnly}
                onClick={() => {
                  const _list = [...quotationTableList];
                  // addTableItem()
                  _list.push(addTableItem());

                  setQuotationTableList(_list);
                }}
              >
                插入表
              </Button>
            </Col>
            <Col
              span={24}
              style={{
                display: quotationTableList?.length > 1 ? "" : "none",
              }}
            >
              <Card title="合计区">
                <Row justify="space-between">
                  <Col span={10}>
                    {quotationTotalPrice}-{quotationDiscountPrice}
                  </Col>
                  <Col span={4}>
                    总计金额：¥ {(quotationTotalPrice / 100).toFixed(2)}
                  </Col>
                  <Col span={10}>
                    <Row gutter={[gutter, gutter]} justify={"end"}>
                      <Col style={{ width: 350 }}>
                        <CheckboxInput
                          disabled={readOnly}
                          defaultValue={quotationDiscountPrice / 100}
                          onChange={async (ev, ckecked) => {
                            //
                            console.log(ev, ckecked);
                            if (!ckecked) {
                              setQuotationDiscountRate(0);
                              setQuotationDiscountPrice(0);
                            } else {
                              setQuotationDiscountPrice((ev || 0) * 100);
                              calcData();
                            }
                          }}
                        />
                      </Col>
                      <Col>
                        <Input
                          disabled
                          style={{ width: 150 }}
                          value={(quotationDiscountRate || 0).toFixed(2)}
                          addonAfter="折扣(%)"
                        />
                      </Col>
                    </Row>
                  </Col>
                </Row>
              </Card>
            </Col>
            <Col span={24}>
              <div className={styles.progress}>
                <div className={styles["progress-text"]}>
                  <span>{(quotationProfitRate || 0).toFixed(2)}%</span>
                </div>
                <div className={styles.p3}></div>
                <div className={styles.p5}></div>
                <div className={styles.p7}></div>
                <div
                  className={styles.value}
                  style={{
                    width: `${quotationProfitRate}%`,
                  }}
                ></div>
              </div>
            </Col>
          </Row>
        </Spin>
      </Drawer>
      {openProduct ? (
        <SelectProduct
          onOk={(data) => {
            const arr = Object.keys(data).map((key) => {
              return data[key];
            });
            const firstItem = arr[0];
            const aftersItems = arr.slice(1);
            console.log("afterItems", aftersItems);
            const {
              id: productId,
              productName,
              modelSpecification,
              guidancePrice: originalGuidancePrice,
              supplyPrice: originalSupplyPrice,
              unit: originalUnit,
            } = firstItem || {}; //modelSpecification,originalGuidancePrice,originalSupplyPrice,originalUnit

            //  quotationTable.id,
            //  quotationTableCategorieItem.id,
            //  record.id,
            //更新quotationTable -》 quotationTableCategorieList -》 quotationTableCategorieDetailList 的modelSpecification,originalGuidancePrice,originalSupplyPrice,originalUnit字段
            const [quotationTableId, quotationTableCategorieItemId, recordId] =
              ids;
            const productNameField = `${quotationTableId}-${quotationTableCategorieItemId}-${recordId}-productName`;
            const name = `${quotationTableId}-${quotationTableCategorieItemId}-${recordId}-modelSpecification`;
            form.setFieldValue(name, modelSpecification);
            form.setFieldValue(productNameField, productName);

            console.log(data, ids);
            setOpenProduct(false);
            let _list = [...quotationTableList];
            _list = _list.map((_quotationTable) => {
              if (quotationTableId === _quotationTable.id) {
                _quotationTable.quotationTableCategorieList =
                  _quotationTable.quotationTableCategorieList.map(
                    (_category) => {
                      if (quotationTableCategorieItemId === _category.id) {
                        _category.quotationTableCategorieDetailList =
                          _category.quotationTableCategorieDetailList.map(
                            (_detail) => {
                              if (recordId === _detail.id) {
                                console.log(_detail, 333);
                                return {
                                  ..._detail,
                                  productId,
                                  productName,
                                  modelSpecification: modelSpecification || "",
                                  originalGuidancePrice:
                                    originalGuidancePrice || 0,
                                  originalSupplyPrice: originalSupplyPrice || 0,
                                  originalUnit: originalUnit || "",
                                };
                              }
                              return {
                                ..._detail,
                              };
                            }
                          );
                      }
                      return {
                        ..._category,
                      };
                    }
                  );
              }
              return {
                ..._quotationTable,
              };
            });
            //如果还有
            if (aftersItems && aftersItems?.length) {
              // 新增一条到quotationTableCategorieDetailList
              _list = _list.map((_quotationTable) => {
                if (quotationTableId === _quotationTable.id) {
                  _quotationTable.quotationTableCategorieList =
                    _quotationTable.quotationTableCategorieList.map(
                      (_category) => {
                        if (quotationTableCategorieItemId === _category.id) {
                          const newDetails = aftersItems.map((item) => {
                            const {
                              id: productId,
                              modelSpecification,
                              productName,
                              guidancePrice: originalGuidancePrice,
                              supplyPrice: originalSupplyPrice,
                              unit: originalUnit,
                            } = item;
                            return {
                              ...addquotationTableCategorieDetailListItem(),
                              productId,
                              productName,
                              modelSpecification: modelSpecification || "",
                              originalGuidancePrice: originalGuidancePrice || 0,
                              originalSupplyPrice: originalSupplyPrice || 0,
                              originalUnit: originalUnit || "",
                            };
                          });
                          _category.quotationTableCategorieDetailList =
                            _category.quotationTableCategorieDetailList.concat(
                              newDetails
                            );
                        }
                        return {
                          ..._category,
                        };
                      }
                    );
                }
                return {
                  ..._quotationTable,
                };
              });
            }
            setQuotationTableList(_list);
          }}
          onClose={() => setOpenProduct(false)}
        />
      ) : null}
    </>
  );
};
export default App;
